package com.api.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.api.common.Common;
import com.api.common.reqres.Request;
import com.api.common.reqres.RequestHead;
import com.api.common.reqres.Response;
import com.api.component.CacheComponent;
import com.api.component.JwtComponent;
import com.api.component.MD5UtilComponent;
import com.api.component.RequestComponent;
import com.api.component.ResponseComponent;
import com.api.mapper.BackstageUserMapper;
import com.api.mapper.MenuMapper;
import com.api.mapper.RoleMapper;
import com.api.mapper.RoleMenuMapper;
import com.api.model.entity.BackstageUser;
import com.api.model.entity.Menu;
import com.api.model.entity.Role;
import com.api.model.entity.RoleMenu;
import com.api.model.request.AddUserRequest;
import com.api.model.request.BackstageUserLoginRequest;
import com.api.model.request.UpdatePasswdRequest;
import com.api.model.request.UpdateUserInfoRequest;
import com.api.model.response.BackstageUserLoginResponse;
import com.api.model.response.NullResponse;
import com.api.service.BackstageUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author cfp
 * @since 2019-10-21
 */
@Service
public class BackstageUserServiceImpl extends ServiceImpl<BackstageUserMapper, BackstageUser>
		implements BackstageUserService {

	@Autowired
	private RequestComponent requestComponent;
	@Autowired
	private ResponseComponent responseComponent;
	@Autowired
	private BackstageUserMapper backstageUserMapper;
	@Autowired
	private RoleMapper roleMapper;
	@Autowired
	private RoleMenuMapper roleMenuMapper;
	@Autowired
	private MenuMapper menuMapper;
	@Autowired
	private MD5UtilComponent md5UtilComponent;
	@Autowired
	private JwtComponent jwtComponent;
	@Autowired
	private CacheComponent cacheComponent;

	@Override
	public Response<BackstageUserLoginResponse> backstageUserLogin(Request<BackstageUserLoginRequest> request) {
		// TODO Auto-generated method stub
		BackstageUserLoginRequest loginRequest = request.getBody();
		requestComponent.checkBody(loginRequest, BackstageUserLoginRequest.class);
		String passwdMd5 = md5UtilComponent.md5(loginRequest.getPasswd());
		LambdaQueryWrapper<BackstageUser> queryWrapper = new LambdaQueryWrapper<BackstageUser>();
		queryWrapper.eq(BackstageUser::getUsername, loginRequest.getUsername()).eq(BackstageUser::getPasswd, passwdMd5)
				.eq(BackstageUser::getStatus, true);
		BackstageUser backstageUser = backstageUserMapper.selectOne(queryWrapper);
		if (Objects.isNull(backstageUser)) {
			return responseComponent.toError("用户名或密码错误!");
		}
		BackstageUserLoginResponse response = new BackstageUserLoginResponse();
		// 获取用户角色和菜单
		// 获取角色
		LambdaQueryWrapper<Role> roleQueryWrapper = new LambdaQueryWrapper<Role>();
		roleQueryWrapper.eq(Role::getOid, backstageUser.getRoleid()).eq(Role::getStatus, true);
		Role role = roleMapper.selectOne(roleQueryWrapper);
		// 获取角色菜单
		if (!Objects.isNull(role)) {
			LambdaQueryWrapper<RoleMenu> roleMenuQueryWrapper = new LambdaQueryWrapper<RoleMenu>();
			roleMenuQueryWrapper.eq(RoleMenu::getRoleid, role.getOid()).eq(RoleMenu::getStatus, true);
			List<RoleMenu> roleMenuList = roleMenuMapper.selectList(roleMenuQueryWrapper);
			// 获取菜单
			List<Menu> menuList = new ArrayList<Menu>();
			for (RoleMenu roleMenu : roleMenuList) {
				LambdaQueryWrapper<Menu> menuQueryWrapper = new LambdaQueryWrapper<Menu>();
				menuQueryWrapper.eq(Menu::getOid, roleMenu.getMenuid()).eq(Menu::getStatus, true);
				Menu menu = menuMapper.selectOne(menuQueryWrapper);
				menuList.add(menu);
			}
			response.setMenuList(menuList);
		}
		response.setBackstageUser(backstageUser);

		response.setRole(role);
		// 设置token信息
		String userid = backstageUser.getOid() + "";
		String key = String.format(Common.USER_TOKEN_TEMPLATE, userid, Common.LOGIN_SOURCE_BACKSTAGE);
		String token = jwtComponent.createToken(key).getToken();
		response.setToken(token);
		// 放到缓存
		String cacheKey = md5UtilComponent.md5(Common.TOKEN + userid + Common.LOGIN_SOURCE_BACKSTAGE).toUpperCase();
		cacheComponent.setCacheToken(cacheKey, token);
		return responseComponent.toSuccess(response);
	}

	@Override
	public Response<NullResponse> updatePasswd(Request<UpdatePasswdRequest> request) {
		// TODO Auto-generated method stub
		RequestHead head = request.getHead();
		UpdatePasswdRequest updatePasswdRequest = request.getBody();
		requestComponent.checkBody(updatePasswdRequest, UpdatePasswdRequest.class);
		String passwdMd5 = md5UtilComponent.md5(updatePasswdRequest.getPasswd());
		BackstageUser backstageUser = new BackstageUser();
		backstageUser.setUpdatetime(LocalDateTime.now());
		backstageUser.setUpdateuser(head.getUserid());
		BeanUtils.copyProperties(updatePasswdRequest, backstageUser);
		backstageUser.setPasswd(passwdMd5);
		backstageUserMapper.updateById(backstageUser);
		return responseComponent.toSuccess(null);
	}

	@Override
	public Response<NullResponse> addUser(Request<AddUserRequest> request) {
		// TODO Auto-generated method stub
		RequestHead head = request.getHead();
		AddUserRequest addUserRequest = request.getBody();
		requestComponent.checkBody(addUserRequest, AddUserRequest.class);
		// 判断用户名是否存在
		LambdaQueryWrapper<BackstageUser> queryWrapper = new LambdaQueryWrapper<BackstageUser>();
		queryWrapper.eq(BackstageUser::getUsername, addUserRequest.getUsername());
		BackstageUser existUser = backstageUserMapper.selectOne(queryWrapper);
		if (!Objects.isNull(existUser)) {
			return responseComponent.toError("用户名已存在!");
		}
		// 保存用户
		String passwdMd5 = md5UtilComponent.md5(Common.DEFAULT_PASSWD);
		BackstageUser backstageUser = new BackstageUser();
		backstageUser.setCreateuser(head.getUserid());
		backstageUser.setCreatetime(LocalDateTime.now());
		BeanUtils.copyProperties(addUserRequest, backstageUser);
		backstageUser.setPasswd(passwdMd5);
		backstageUserMapper.insert(backstageUser);
		return responseComponent.toSuccess(null);
	}

	@Override
	public Response<NullResponse> updateUserInfo(Request<UpdateUserInfoRequest> request) {
		// TODO Auto-generated method stub
		UpdateUserInfoRequest updateUserInfoRequest = request.getBody();
		requestComponent.checkBody(updateUserInfoRequest, UpdateUserInfoRequest.class);

		// 判断用户名是否存在
		LambdaQueryWrapper<BackstageUser> queryWrapper = new LambdaQueryWrapper<BackstageUser>();
		queryWrapper.eq(BackstageUser::getUsername, updateUserInfoRequest.getUsername()).ne(BackstageUser::getOid,
				updateUserInfoRequest.getOid());
		int count = backstageUserMapper.selectCount(queryWrapper);
		if (count > 0) {
			return responseComponent.toError("用户名已存在!");
		}

		BackstageUser backstageUser = new BackstageUser();
		BeanUtils.copyProperties(updateUserInfoRequest, backstageUser);
		backstageUserMapper.updateById(backstageUser);
		return responseComponent.toSuccess(null);
	}

}
